<template>
    <div v-if="visible">
        <el-dialog :title="$t('serviceRequest.serviceRequest')"
                   ref="dialog"
                   top="10"
                   :visible="visible"
                   @close="close"
                   destroy-on-close
                   width="100%">
            <el-form :model="quest" :rules="rule" label-width="150px" ref="quest">
                <div style="display: flex">
                    <div class="wrapper-content">
                        <el-form-item :label="$t('serviceRequest.requestNo')">
                            <el-input v-model="quest.requestName" :placeholder="$t('serviceRequest.requestNo')" size="small" class="my-input"></el-input>
                        </el-form-item>
                        <el-form-item :label="$t('serviceRequest.customer')">
                            <!--<el-input v-model="quest.customerName" disabled class="my-input" size="small"/>-->
                            <el-select filterable
                                       v-model="quest.customerId"
                                       clearable
                                       :placeholder="$t('serviceRequest.customer')"
                                       size="small"
                                       class="my-input">
                                <el-option
                                        v-for="item in customerList"
                                        :key="item.customerId"
                                        :label="item.customerName"
                                        :value="item.customerId">
                                </el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item :label="$t('serviceRequest.requestDate')" prop="requestDate">
                            <el-date-picker
                                    class="my-input"
                                    v-model="quest.requestDate"
                                    type="datetime"
                                    :placeholder="$t('serviceRequest.requestDate')"
                                    value-format="yyyy-MM-dd HH:mm:ss"
                                    size="small"
                            ></el-date-picker>
                        </el-form-item>
                        <el-form-item :label="$t('serviceRequest.requestBy')" prop="initiator">
                            <el-select v-model="quest.initiator" filterable class="my-input" size="small">
                                <el-option v-for="item in customerContactList" :key="item.contactId" :value="item.contactId"
                                           :label="item.contactName "></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item :label="$t('serviceRequest.operator')" prop="operator">
                            <el-select v-model="quest.operator" filterable class="my-input" size="small">
                                <el-option v-for="item in customerContactList" :key="item.contactId" :value="item.contactId"
                                           :label="item.contactName"></el-option>
                            </el-select>
                        </el-form-item>

                    </div>
                    <div class="wrapper-content">
                        <el-form-item :label="$t('serviceRequest.plateNum')" prop="plateNum">
                            <el-select v-model="quest.plateNum" filterable class="my-input" size="small">
                                <el-option v-for="item in plateList" :key="item" :value="item" :label="item"/>
                            </el-select>
                        </el-form-item>
                        <el-form-item :label="$t('serviceRequest.unit')">
                            <el-input v-model="quest.unitModel" disabled size="small" class="my-input"/>
                        </el-form-item>
                        <el-form-item :label="$t('serviceEquipment.engineType')">
                            <el-input v-model="quest.engineType" disabled size="small" class="my-input"/>
                        </el-form-item>
                        <el-form-item :label="$t('serviceRequest.sn')">
                            <el-input v-model="quest.sn" disabled size="small" class="my-input"/>
                        </el-form-item>
                        <el-form-item :label="$t('serviceRequest.deliveryTime')">
                            <el-input v-model="quest.deliveryTime" disabled size="small" class="my-input"/>
                        </el-form-item>
                        <el-form-item :label="$t('serviceRequest.hmkm')">
                            <el-input v-model="quest.hmKm" size="small" class="my-input"/>
                        </el-form-item>
                        <el-form-item :label="$t('serviceRequest.serviceType')" prop="typeCode">
                            <el-select v-model="quest.typeCode" size="small" class="my-input">
                                <el-option :value="1" label="Maintaince"/>
                                <el-option :value="2" label="Repair"/>
                                <el-option :value="3" label="Warrenty"/>
                                <el-option :value="4" label="Tire"/>
                            </el-select>
                        </el-form-item>

                        <el-form-item :label="$t('serviceRequest.notes')">
                            <el-input v-model="quest.notes" type="textarea" size="small" class="my-input"/>
                        </el-form-item>
                    </div>
                    <div class="wrapper-content">
                        <el-form-item :label="$t('serviceRequest.problem')">
                            <div class="problem" v-for="(item,index) in quest.problems" :key="index"
                                 style="position: relative;margin-bottom: 10px;">
                                <el-input v-model="item.problemDescription" type="textarea" size="small"
                                          class="my-input"/>
                                <el-button @click="showProblem(item,index)" type="warning"
                                           style="width: 20px;height: 20px;padding: 0;vertical-align: middle;margin-left: 10px;margin-bottom: 12px;">
                                    <i class="el-icon-document"/>
                                </el-button>
                            </div>
                            <el-button @click="addProblem" type="primary"
                                       style="width: 20px;height: 20px;padding: 0;vertical-align: top;position: absolute;top: 15px;right: 0px;">
                                <i class="el-icon-plus"/>
                            </el-button>
                        </el-form-item>
                    </div>
                </div>

            </el-form>

            <span slot="footer" class="dialog-footer">
                        <el-button @click="close">{{$t('cancel')}}</el-button>
                        <el-button type="info" @click="submitForm">{{$t('save')}}</el-button>
                        <el-button type="primary" @click="submitForm">{{$t('confirm')}}</el-button>
                    </span>
        </el-dialog>
        <problem :visible="fileShow" :picture="picture" :video="video" :file="file" @close="close1" @sub="sub"/>
    </div>

</template>

<script>
    import { getEmployeeList, getRequestNo, getPlateNo, getDeviceInfo,subQuest,modQuest,showQuestDetail,getProject} from "../../api/service";
    import {getCustomerList} from "../../api";
    import {ERROR_OK} from "../../util/config";
    import problem from './problem'
    import {getContactList} from "../../api/customer";

    export default {
        name: "quest-dialog",
        props: {
            visible: Boolean,
            id: Number
        },
        created() {
            this._getEmployeeList();
            this._getCustomerList();
            this._getDetail(this.id);
            // this._getPlate();
            this.getProject()
        },
        data() {
            return {
                quest: {
                    requestName:'',
                    requestNo: '',
                    requestDate: '',
                    initiator: '',
                    operator:'',
                    customerId: '',
                    customerName: '',
                    addressId: '',
                    address: '',
                    distance: '',
                    engineType:'',
                    unitModel: '',
                    sn: '',
                    deliveryTime: '',
                    hmKm: '',
                    typeCode: '',
                    serviceType: "",
                    appointmentTime: '',
                    note: '',
                    status: "",
                    projectName: '',
                    plateNum: '',
                    charges: [],
                    reason:'',
                    problems: [{
                        problemDescription: '',
                        problemPhoto: [],
                        problemVideo: [],
                        problemFile: []
                    }],
                    id: '',
                },
                rule:{
                    // projectName:[{required:true,message:'A project is required'}],
                    plateNum:[{required:true,message:'A plateNum is required'}],
                    typeCode:[{required:true,message:'Service Type is required'}],
                    initiator:[{required:true,message:'Request by is required'}],
                    operator:[{required:true}],
                    requestDate:[{required:true,message:'Request Date is required'}]
                },
                employeeList: [],
                customerList: [],
                customerContactList:[],
                projectList:[],
                plateList: [],
                picture: [],
                video: [],
                file: [],
                fileShow: false,
                index:'',
                current:{}
            }
        },
        methods: {
            showProblem(item,index) {
                this.picture = item.problemPhoto;
                this.video = item.problemVideo;
                this.file = item.problemFile;
                this.current = item;
                this.index = index;
                this.fileShow = true
            },
            sub(file){
                const current = {...this.current,...file};
                this.quest.problems.splice(this.index,1,current);
                this.close1();
            },
            close1(){
                this.fileShow = false
            },
            addProblem() {
                this.quest.problems = this.quest.problems.concat([{
                    problemDescription: '',
                    problemPhoto: [],
                    problemVideo: [],
                    problemFile: []
                }])
            },
            async getProject(){
                const {status,data} = await getProject()
                if(status === ERROR_OK) {
                    this.projectList = data
                }
            },
            async submitForm() {
                const {
                    id,
                    requestName,
                    requestNo,
                    requestDate,
                    initiator,
                    customerId,
                    customerName,
                    distance,
                    unitModel,
                    engineType,
                    sn,
                    deliveryTime,
                    hmKm,
                    typeCode,
                    serviceType,
                    operator,
                    appointmentTime,
                    note,
                    status,
                    projectName,
                    plateNum,
                } = this.quest;
                let problems = this.quest.problems;
                problems.forEach(problem=>{
                    problem.problemPhoto =  problem.problemPhoto?problem.problemPhoto.join(','):'';
                    problem.problemVideo =  problem.problemVideo?problem.problemVideo.join(','):'';
                    problem.problemFile =   problem.problemFile?problem.problemFile.join(','):'';
                });
                problems = JSON.stringify(problems);
                this.$refs.quest.validate(async valid=>{
                   if(valid) {
                       if(!this.id) {
                           const {status:status1,msg} = await subQuest({requestNo,
                               requestDate,
                               initiator,
                               customerId,
                               customerName,
                               requestName,
                               distance,
                               operator,
                               engineType,
                               unitModel,
                               sn,
                               deliveryTime,
                               hmKm,
                               typeCode,
                               serviceType,
                               appointmentTime,
                               note,
                               status,
                               projectName,
                               plateNum,
                               problems});
                           if (status1 === ERROR_OK) {
                               this.$message.success('Add Successfully');
                               this.quest = {
                                   requestName:'',
                                   requestNo: '',
                                   requestDate: '',
                                   initiator: '',
                                   customerId: '',
                                   customerName: '',
                                   addressId: '',
                                   address: '',
                                   distance: '',
                                   engineType:'',
                                   unitModel: '',
                                   sn: '',
                                   deliveryTime: '',
                                   hmKm: '',
                                   typeCode: '',
                                   serviceType: "",
                                   appointmentTime: '',
                                   note: '',
                                   status: "",
                                   projectName: '',
                                   plateNum: '',
                                   charges: [],
                                   reason:'',
                                   problems: [{
                                       problemDescription: '',
                                       problemPhoto: [],
                                       problemVideo: [],
                                       problemFile: []
                                   }],
                                   id: '',
                               };
                               this.$emit('addSuccess');
                           } else {
                               this.$message.error(msg)
                           }
                       } else {
                           const {status:status1} = await modQuest({requestNo,
                               id,
                               requestName,
                               requestDate,
                               operator,
                               initiator,
                               customerId,
                               customerName,
                               distance,
                               unitModel,
                               sn,
                               deliveryTime,
                               hmKm,
                               engineType,
                               typeCode,
                               serviceType,
                               appointmentTime,
                               note,
                               status,
                               projectName,
                               plateNum,
                               problems});
                           if (status1 === ERROR_OK) {
                               this.$message.success('Modify Successfully');
                               this.quest = {
                                   requestName:'',
                                   requestNo: '',
                                   requestDate: '',
                                   initiator: '',
                                   customerId: '',
                                   customerName: '',
                                   addressId: '',
                                   address: '',
                                   distance: '',
                                   unitModel: '',
                                   engineType:'',
                                   sn: '',
                                   deliveryTime: '',
                                   hmKm: '',
                                   typeCode: '',
                                   serviceType: "",
                                   appointmentTime: '',
                                   note: '',
                                   status: "",
                                   projectName: '',
                                   plateNum: '',
                                   charges: [],
                                   reason:'',
                                   problems: [{
                                       problemDescription: '',
                                       problemPhoto: [],
                                       problemVideo: [],
                                       problemFile: []
                                   }],
                                   id: '',
                               };
                               this.$emit('addSuccess');
                           } else {
                               this.$message.error('Pls retry')
                           }
                       }
                   } else {
                       this.$notify.warning('Please complete the form')
                   }
                });

            },
            close() {
                this.$emit('close');
                this.quest = {
                    requestNo: '',
                    requestDate: '',
                    initiator: '',
                    customerId: '',
                    customerName: '',
                    addressId: '',
                    address: '',
                    distance: '',
                    unitModel: '',
                    sn: '',
                    deliveryTime: '',
                    hmKm: '',
                    typeCode: '',
                    engineType:'',
                    serviceType: "",
                    appointmentTime: '',
                    note: '',
                    status: "",
                    projectName: '',
                    plateNum: '',
                    charges: [],
                    reason:'',
                    problems: [{
                        problemDescription: '',
                        problemPhoto: [],
                        problemVideo: [],
                        problemFile: []
                    }],
                    id: '',
                };
            },
            async _getPlate(customer) {
                const {status, data} = await getPlateNo(customer);
                if (status === ERROR_OK) {
                    this.plateList = data
                }
            },
            async _getRequestNo() {
                const {status, data} = await getRequestNo();
                if (status === ERROR_OK) {
                    this.quest.requestNo = data
                }
            },
            async _getCustomerList() {
                const {status, data} = await getCustomerList(3);
                if (status === ERROR_OK) {
                    this.customerList = data
                }
            },
            async _getEmployeeList() {
                const {status, data} = await getEmployeeList();
                if (status === ERROR_OK) {
                    this.employeeList = data
                }
            },
            async _getDeviceInfo(plateNum) {
                const {status, data} = await getDeviceInfo({plateNum});
                if (status === ERROR_OK) {
                    this.quest.unitModel = data.model;
                    this.quest.sn = data.sn;
                    this.quest.deliveryTime = data.arrieveDateStr;
                    this.quest.engineType = data.engineType;
                }
            },
            async _getDetail(id) {
                const {status,data} = await showQuestDetail(id);
                if(status === ERROR_OK) {
                    this.quest = data.orderVo;
                    if(data.problemVoList.length){
                        this.$set(this.quest,'problems',data.problemVoList);
                    }else {
                        this.$set(this.quest,'problems',[{
                            problemDescription: '',
                            problemPhoto: [],
                            problemVideo: [],
                            problemFile: []
                        }])
                    }
                    this.quest.problems = data.problemVoList

                }
            },
            async getCustomerContactListByName(customer){
                // this.$set(this.quest,'initiator','');
                this.customerContactList = []
                const id = this.customerList.find(item => item.customerName === customer).customerId;
                const {status, data} = await getContactList(id);
                if (status === ERROR_OK) {
                    this.customerContactList = data;
                } else {
                    this.customerContactList = []
                }
            },

        },
        watch: {
            id(id) {
                if(id) {
                    this._getDetail(id);
                }
            },
            visible(visible) {
                if (visible && !this.id) {
                    this._getRequestNo()
                }
            },
            "quest.plateNum": {
                handler(plateNum) {
                    if(!plateNum){
                        return
                    }
                    this._getDeviceInfo(plateNum)
                },
            },
            "quest.customerId":{
                handler(id) {
                    if(id) {
                        const customer = this.customerList.find(item=>item.customerId === id).customerName;
                        this.quest.customerName = customer
                        this.getCustomerContactListByName(customer);
                        this._getPlate(customer);
                    } else  {
                        this.plateList = [];
                        this.$set(this.quest,'plateNum','');
                        this.$set(this.quest,'unitModel','');
                        this.$set(this.quest,'deliveryTime','');
                        this.$set(this.quest,'sn','');
                    }
                }
            }

        },
        components: {
            problem
        }
    }
</script>

<style scoped lang="scss">
    .wrapper-content {
        flex: 1;
    }
</style>